package exam.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import exam.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/24 20:04
 * @since JDK 1.8
 *
 * 对响应体做一些统一的操作
 */
@Slf4j
@Order(1)
@RestControllerAdvice
public class RequestAdvice {


    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(HttpServletRequest request, RuntimeException ex) {
        log.error("", ex);
        log.error("请求地址：" + request.getRequestURL());
        log.error("请求参数: " + JSONUtil.toJsonStr(request.getParameterMap()));
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    /**
     * 用来捕获404，400这种无法到达controller的错误
     *
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public JSONObject defaultErrorHandler(Exception ex) throws Exception {
        log.error("", ex);
        JSONObject jsonObject= Result.errorObject();
        if (ex instanceof NoHandlerFoundException) {
            jsonObject.put("code",400);
        } else {
            jsonObject.put("code",500);
        }
        jsonObject.put("msg","");
        return jsonObject;
    }
}
